/*
 * Powered By [rapid-framework]
 * Web Site: http://www.rapid-framework.org.cn
 * Google Code: http://code.google.com/p/rapid-framework/
 * Since 2008 - 2013
 */


package com.smg.community.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javacommon.base.BaseRestSpringController;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.org.rapid_framework.page.Page;

import com.smg.community.model.SmgGroup;
import com.smg.community.model.SmgGroupCategory;
import com.smg.community.model.SmgGroupMember;
import com.smg.community.model.SmgMember;
import com.smg.community.model.SmgMemberFocus;
import com.smg.community.model.SmgTopic;
import com.smg.community.setting.Constant;
import com.smg.community.util.ProjectUtil;
import com.smg.community.vo.query.SmgGroupQuery;
import com.smg.community.vo.query.SmgTopicQuery;

/**
 * @author badqiu email:badqiu(a)gmail.com
 * @version 1.0
 * @since 1.0
 */

@Controller
@RequestMapping("/group")
public class SmgGroupController extends BaseRestSpringController<SmgGroup,java.lang.Integer>{
	Log logger = LogFactory.getLog(SmgGroupController.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	
	private void setGroupDetailRightCommonModel(ModelMap model,HttpServletRequest request,int pageNumber,SmgGroup group){
		//右侧相关小组,获取相同分类下三个人数最多的  
		SmgGroupQuery groupQuery = new SmgGroupQuery();
		groupQuery.setStart(0);
		groupQuery.setLimit(3);
		groupQuery.setFkCateId(group.getFkCateId());
		groupQuery.setOrderBy( "memberCount desc ");
		List<SmgGroup> sameCateGroupList = smgGroupManager.getByQuery(groupQuery);  
		model.addAttribute("sameCateGroupList",sameCateGroupList);
		//右侧最新加入本群组的成员 按加入日期排序
		List<SmgMember> memberList = smgMemberManager.getFourLastedJoinGroupMember(group.getGroupId());
		model.addAttribute("memberList",memberList);
		SmgMember loginMember = getLoginMember(request);
		if (  loginMember != null ){
			for (SmgMember member:memberList){
				SmgMemberFocus smgMemberFocus = smgMemberFocusManager.getByMemberIdAndFocuseId(loginMember.getMemberId(),member.getMemberId());
				if ( smgMemberFocus!=null ){
					member.setFocusDate(smgMemberFocus.getFocusDate());
				}
			}
		}
		//右侧推荐话题 按点击数排序
		SmgTopicQuery query = new SmgTopicQuery();
		query.setTopType(" toptype> 0 ");
		query.setFkCateId(group.getFkCateId());
		query.setPageNumber(pageNumber);
		setStartAndLimit(query, pageNumber);
		query.setLimit(3);
		query.setOrderBy("replycount desc");
		List<SmgTopic> topicList =  smgTopicManager.getByQuery(query);
		for(SmgTopic topic:topicList){
			ProjectUtil.filterTopic(topic);
		}
		model.addAttribute("topicList",topicList);
		int masterCount  = 0;
		int joinCount = 0 ;
		if ( getLoginMember(request) != null ){
			masterCount = smgGroupManager.getMemberMastetGroupCount(getLoginMember(request).getMemberId());
			joinCount = smgGroupManager.getMemberJoinGroupCount(getLoginMember(request).getMemberId());
			model.addAttribute("masterCount",joinCount);
			model.addAttribute("joinCount",masterCount);
		}
		//
		if ( loginMember == null){
			model.addAttribute("isMaster",false);
			model.addAttribute("isGroupMember",false);
		}else{
		//	setRightGroup(loginMember,model);
			if ( loginMember.getMemberId() == group.getFkMemberId()){
				model.addAttribute("isMaster",true);
				model.addAttribute("isGroupMember",true);
			}else{
				model.addAttribute("isMaster",false);
				int memberId = loginMember.getMemberId();
				SmgGroupMember groupMember = smgGroupMemberManager.getByGroupIdAndMemberId(group.getGroupId(),memberId);
				if (groupMember == null){
					model.addAttribute("isGroupMember",false);
				}else{
					model.addAttribute("isGroupMember",true);
				}
			}
		}
	}
	/**
	 * 群组-帖子
	 * @param id
	 * @param orderBy
	 * @param pageNumber
	 * @param request
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/detail/d/{id}-{pageNumber}-{orderBy}")
	public String intoGroupDetail(@PathVariable int id,@PathVariable int orderBy,@PathVariable int pageNumber,HttpServletRequest request,ModelMap model){
		try {
			SmgGroup group = smgGroupManager.getById(id);
			if ( group == null){
				model.addAttribute("message","很抱歉,群组不存在,去别的群组转转吧");
				return toErrorPage(model, "很抱歉,群组不存在,去别的群组转转吧");
			}
			setHeadTabIndex(model,Constant.GROUP_TAB);
			setCommunityCommonModel(request, model);
			int groupId = group.getGroupId();
			model.addAttribute("group",group);
			SmgTopicQuery query = new SmgTopicQuery();
			logger.debug(orderBy);
			query.setFkGroupId(groupId);
			query.setTopType(" toptype = 0 ");
			query.setPageNumber(pageNumber);
			setStartAndLimit(query, pageNumber);
			Page<SmgTopic> topicPage = smgTopicManager.findPage(query);
			model.addAttribute("topicPage",topicPage);
			for(SmgTopic topic:topicPage) {
				ProjectUtil.filterTopic(topic);
			}
			int cityNo = group.getCityNo();
			int cateId = group.getFkCateId();
			setGroupDetailRightCommonModel(model, request, pageNumber, group);
			//全站置顶帖
			List<SmgTopic> fullSiteTopList ;
			query = new SmgTopicQuery();
			query.setCityNo(cityNo);
			query.setTopType("toptype="+Constant.FULL_SIZT_TOP_TYPE);
			query.setStart(0);
			query.setLimit(100);
			fullSiteTopList = smgTopicManager.getByQuery(query);
			model.addAttribute("fullSiteTopList",fullSiteTopList);
			//分类置顶帖
			List<SmgTopic> cateGoryTopList ;
			query = new SmgTopicQuery();
			query = new SmgTopicQuery();
			query.setCityNo(cityNo);
			query.setTopType("toptype="+Constant.CATEGORY_TOP_TYPE);
			query.setFkCateId(cateId);
			query.setStart(0);
			query.setLimit(100);
			cateGoryTopList = smgTopicManager.getByQuery(query);
			model.addAttribute("cateGoryTopList",cateGoryTopList);
			//组内置顶帖
			List<SmgTopic> groupTopList ;
			query = new SmgTopicQuery();
			query = new SmgTopicQuery();
			query.setCityNo(cityNo);
			query.setTopType("toptype="+Constant.GROUP_TOP_TYPE);
			query.setFkCateId(cateId);
			query.setStart(0);
			query.setLimit(100);
			groupTopList = smgTopicManager.getByQuery(query);
			model.addAttribute("groupTopList",groupTopList);
			
			
			//页面查询参数
			model.addAttribute("cateId",cateId);
			model.addAttribute("cityNo",cityNo);
			model.addAttribute("pageNumber",pageNumber);
			model.addAttribute("orderBy",orderBy);
			
			
			model.addAttribute("type","topic");
			
		
		}catch(Exception e){
			e.printStackTrace();
			return toErrorPage(model, e);
		}
		return "/group/detail";
	}

	/**
	 * 群组-活动
	 * @param id
	 * @param orderBy
	 * @param pageNumber
	 * @param request
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/detail/a/{id}-{pageNumber}-{orderBy}")
	public String intoGroupActivity(@PathVariable int id,@PathVariable int orderBy,@PathVariable int pageNumber,HttpServletRequest request,ModelMap model){
		try {
			SmgGroup group = smgGroupManager.getById(id);
			if ( group == null){
				model.addAttribute("message","很抱歉,群组不存在,去别的群组转转吧");
				return "/common/error";
			}
			setHeadTabIndex(model,Constant.GROUP_TAB);
			setCommunityCommonModel(request, model);
			int groupId = group.getGroupId();
			model.addAttribute("group",group);
			SmgTopicQuery query = new SmgTopicQuery();
			query.setFkGroupId(groupId);
			query.setPageNumber(pageNumber);
			query.setTopicType(Constant.TOPIC_TYPE_ACTIVITY);
			setStartAndLimit(query, pageNumber);
			Page<SmgTopic> topicPage = smgTopicManager.findActivityPage(query);
			for(SmgTopic topic:topicPage) {
				ProjectUtil.filterTopic(topic);
			}
			model.addAttribute("topicPage",topicPage);
			setGroupDetailRightCommonModel(model, request, pageNumber, group);
			int cityNo = group.getCityNo();
			int cateId = group.getFkCateId();
			//全站置顶帖
			List<SmgTopic> fullSiteTopList ;
			query = new SmgTopicQuery();
			query.setCityNo(cityNo);
			query.setTopType("toptype="+Constant.FULL_SIZT_TOP_TYPE);
			query.setStart(0);
			query.setLimit(100);
			fullSiteTopList = smgTopicManager.getByQuery(query);
			model.addAttribute("fullSiteTopList",fullSiteTopList);
			//分类置顶帖
			List<SmgTopic> cateGoryTopList ;
			query = new SmgTopicQuery();
			query = new SmgTopicQuery();
			query.setCityNo(cityNo);
			query.setTopType("toptype="+Constant.CATEGORY_TOP_TYPE);
			query.setFkCateId(cateId);
			query.setStart(0);
			query.setLimit(100);
			cateGoryTopList = smgTopicManager.getByQuery(query);
			model.addAttribute("cateGoryTopList",cateGoryTopList);
			//组内置顶帖
			List<SmgTopic> groupTopList ;
			query = new SmgTopicQuery();
			query = new SmgTopicQuery();
			query.setCityNo(cityNo);
			query.setTopType("toptype="+Constant.GROUP_TOP_TYPE);
			query.setFkCateId(cateId);
			query.setStart(0);
			query.setLimit(100);
			groupTopList = smgTopicManager.getByQuery(query);
			model.addAttribute("groupTopList",groupTopList);
			
			
			//页面查询参数
			model.addAttribute("cateId",cateId);
			model.addAttribute("cityNo",cityNo);
			model.addAttribute("pageNumber",pageNumber);
			model.addAttribute("orderBy",orderBy);
			
			model.addAttribute("type","activity");
			
			
			
		}catch(Exception e){
			e.printStackTrace();
			return toErrorPage(model, e);
		}
		return "/group/detail";
	}
	@RequestMapping(value="/detail/{id}")
	public String intoGroupDetailDefault(@PathVariable int id ,HttpServletRequest request,ModelMap model){
			return intoGroupDetail(id,1,1,request,model);
	}
	@RequestMapping(value="/detail/{id}-{pageNumber}")
	public String intoGroupDetailByPage(@PathVariable int id ,@PathVariable int pageNumber,HttpServletRequest request,ModelMap model){
			return intoGroupDetail(id,1,pageNumber,request,model);
	}
	
	/**
	 * @param cityNo   城市号
	 * @param cateId   分类ID  0-全部
	 * @param filter   过滤的类型   0-全部  1-我管理的
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/list/{cityNo}-{cateId}-{filter}-{pageNumber}")
	public String intoGroupListOtherCity(@PathVariable int cityNo ,@PathVariable int cateId,@PathVariable int filter,@PathVariable int pageNumber,HttpServletRequest request,ModelMap model){
		setCommunityCommonModel(request, model);
		setHeadTabIndex(model, 2);
		//所有分类
		List<SmgGroupCategory>  categoryList = smgGroupCategoryManager.findAll() ;
		model.addAttribute("categoryList",categoryList);
		SmgGroupQuery query  = new SmgGroupQuery();
		query.setCityNo(cityNo);
		query.setFkCateId(cateId ==0?null:cateId);
		query.setPageNumber(pageNumber);
		query.setPageSize(10);
		setStartAndLimit(query, pageNumber,10);
		if ( filter == 1){
			if ( getLoginMember(request)!=null ){
				query.setFkMemberId(getLoginMember(request).getMemberId());
			}
			Page<SmgGroup> groupPage   = smgGroupManager.findPage(query);
			model.addAttribute("groupPage",groupPage);
		}else if ( filter == 2){
			query.setJoinMemberId(getLoginMember(request).getMemberId());
			Page<SmgGroup> groupPage =   smgGroupManager.findMemberJoinPage(query);
			model.addAttribute("groupPage",groupPage);
		}else{
			Page<SmgGroup> groupPage   = smgGroupManager.findPage(query);
			model.addAttribute("groupPage",groupPage);
		}
	
		if ( getLoginMember(request)!=null ){
			query.setFkCateId(0);
			query.setFkMemberId(getLoginMember(request).getMemberId());
			Page temp =  smgGroupManager.findPage(query);
			model.addAttribute("masterCount", temp.getTotalCount());
			 query  = new SmgGroupQuery();
			query.setLimit(1);
			query.setJoinMemberId(getLoginMember(request).getMemberId());
			Page temp2 = smgGroupManager.findMemberJoinPage(query);
			model.addAttribute("joinCount", temp2.getTotalCount());
		}
		//页面查询参数
		model.addAttribute("cateId",cateId);
		model.addAttribute("cityNo",cityNo);
		model.addAttribute("filter",filter);
		model.addAttribute("pageNumber",pageNumber);
		//好友登录
		SmgMember member  = getLoginMember(request);
		List<SmgMember> fourMemberList = null ;
		if ( member == null){
			//获取推荐的用户
			fourMemberList = smgMemberManager.getFourStaffMember();
		}else{
			fourMemberList = smgMemberManager.getFourFriendMember(member.getMemberId());
			if ( fourMemberList.size() == 0 ){
				fourMemberList = smgMemberManager.getFourStaffMember();
			}
		}
		model.addAttribute("fourMemberList",fourMemberList);
		return   "/group/list";
	}
	

	@RequestMapping(value="")
	public String intoGroupListDefault(@PathVariable int id ,HttpServletRequest request,ModelMap model){
			return    intoGroupListOtherCity(21,0,0,1,request,model);
	}
	@RequestMapping(value="/{cityNo}")
	public String intoGroupListOtherCity(@PathVariable int cityNo ,HttpServletRequest request,ModelMap model){
			return    intoGroupListOtherCity(cityNo,0,0,1,request,model);
	}
	
	@RequestMapping(value="/join/{groupId}")
	@Transactional
	public @ResponseBody Map<String,String> join(@PathVariable int groupId,HttpServletRequest request,ModelMap model){
		SmgMember loginMember = getLoginMember(request);
		Map<String,String> map = new HashMap<String,String>();
		if ( loginMember == null){
			map.put("state", "-1");
			map.put("desc","您未登录或者登录超时");
			return null;
		}
		SmgGroupMember groupMember = new SmgGroupMember();
		groupMember.setFkGroupId(groupId);
		groupMember.setFkMemberId(loginMember.getMemberId());
		smgGroupMemberManager.save(groupMember);
		smgGroupManager.addMemberCount(groupId);
		map.put("state","1");
		map.put("memberCount",smgGroupManager.getById(groupId).getMemberCount()+"");
	
		return map;
	}
	
	
	@RequestMapping(value="/exit/{groupId}")
	@Transactional
	public @ResponseBody Map<String,String> exit(@PathVariable int groupId,HttpServletRequest request,ModelMap model){
		SmgMember loginMember = getLoginMember(request);
		Map<String,String> map = new HashMap<String,String>();
		if ( loginMember == null){
			map.put("state", "-1");
			map.put("desc","您未登录或者登录超时");
			return null;
		}
		smgGroupManager.subMemberCount(groupId);
		smgGroupMemberManager.delete(loginMember.getMemberId(),groupId);
		map.put("memberCount",smgGroupManager.getById(groupId).getMemberCount()+"");
		map.put("state","1");
		return map;
	}
	

}

